<template>
  <el-card style="height: 100%;">
    <el-table :data="MenuInfoList" stripe style="font-size:15px" row-key="ID"
              @row-dblclick="showData($event, true, false)" max-height="1000px"
              :expand-row-keys="expands" @expand-change="ExpandChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column v-if="PERMISSION_BUTTON.CREATE">
        <template #header>
          <el-button size="large" type="success" @click.stop="showData(null, false, false)">
            菜单名称
          </el-button>
        </template>
        <template #default="scope">
          <el-tag size="large"
                  :type="scope.row.MENU_TYPE == 1 ? 'primary': scope.row.MENU_TYPE == 2 ? 'success' : 'danger'">
            {{ scope.row.NAME }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-else>
        <template #header>
          <span>菜单名称</span>
        </template>
        <template #default="scope">
          <el-tag size="large"
                  :type="scope.row.MENU_TYPE == 1 ? 'primary': scope.row.MENU_TYPE == 2 ? 'success' : 'danger'">
            {{ scope.row.NAME }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="PATH" label="路由地址" show-overflow-tooltip/>
      <el-table-column prop="COMPONENT" label="组件路径" show-overflow-tooltip/>
      <el-table-column prop="MENU_TYPE" label="菜单类型" :formatter="MenuTypeInit"/>
      <el-table-column prop="PERMS" label="权限标识" show-overflow-tooltip/>
      <el-table-column prop="ORDER_NUM" label="排序" align="center"/>
      <el-table-column prop="REMARK" label="备注" show-overflow-tooltip>
        <template #header>
          <span @click.stop="collapseColumn = !collapseColumn">备注</span>
          <!--          <el-button v-if="!collapseColumn" size="small" :icon="ArrowRight" circle @click.stop="collapseColumn = true"/>-->
        </template>
      </el-table-column>
      <el-table-column align="left" label="操作" min-width="150" v-if="collapseColumn">
        <template #header>
          <span @click.stop="collapseColumn = !collapseColumn">操作</span>
          <!--          <el-button size="small" :icon="ArrowLeft" circle @click.stop="collapseColumn = false"/>-->
        </template>
        <template #default="scope">
          <el-button v-if="PERMISSION_BUTTON.UPDATE" size="small" type="primary"
                     @click.stop="showData(scope.row, false, true)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click.stop="handleDelete(scope.row)"
            v-if="PERMISSION_BUTTON.DELETE"
          >
            删除
          </el-button>
          <el-button v-if="scope.row.MENU_TYPE != 3 && PERMISSION_BUTTON.CREATE" size="small"
                     type="success"
                     @click.stop="showData(scope.row, false, false)">
            添加
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogFormVisible" width="500">
      <el-form :model="form">
        <el-form-item label="菜单名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth">
          <el-input v-model="form.orderNum" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="路由地址" :label-width="formLabelWidth">
          <el-input v-model="form.path" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="组价路径" :label-width="formLabelWidth">
          <el-input v-model="form.component" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="菜单类型" :label-width="formLabelWidth">
          <el-select-v2
            v-model="form.menuType"
            :options="options"
            style="width: 100%"
            disabled
          />
        </el-form-item>
        <el-form-item label="权限标识" :label-width="formLabelWidth">
          <el-input v-model="form.perms" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" :disabled="dialogDisabled"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false; isEdit = false;">取消</el-button>
          <el-button type="primary" @click="handleEdit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>

import { useStore } from 'vuex';
import { onBeforeMount, reactive, ref, toRefs } from 'vue';
import { get, post } from '@/api/https';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { MENU } from '@/utils/permission';
import { hasPermission } from '@/utils';

export default {
  name: 'TreeMenuView',
  setup() {
    const data = reactive({
      MenuInfoList: [],
      options: [
        {
          label: '目录',
          value: 1
        },
        {
          label: '菜单',
          value: 2
        },
        {
          label: '按钮',
          value: 3
        }
      ],
      expands: [],
      form: {
        id: '',
        name: '',
        parentId: '',
        orderNum: 0,
        path: '',
        component: '',
        menuType: 1,
        perms: '',
        remark: '',
      },
      formLabelWidth: 80,
      PERMISSION_BUTTON: {
        CREATE: false,
        UPDATE: false,
        DELETE: false,
      }
    });

    let dialogFormVisible = ref(false);
    let dialogDisabled = ref(false);
    let collapseColumn = ref(true);
    let isEdit = ref(false); //是否为编辑操作

    //默认只展开一个子菜单处理
    function ExpandChange(row, expandRows) {
      if (expandRows) {
        data.expands = [];
        data.expands.push(row.ID);
        data.expands.push(row.PARENT_ID);
      }
    };

    async function GetTreeMenuList(role_id) {
      const response = await get('/menu/get-tree-list/', {
        id: role_id
      });
      if (response.code == 200) {
        data.MenuInfoList = response.data;
      } else {
        ElMessage({
          message: '获取菜单信息失败',
          type: 'error'
        });
      }
    }

    const handleEdit = () => {
      if (dialogDisabled.value) {
        return;
      }
      ElMessageBox.confirm(`是否确认${isEdit.value ? '修改' : '添加'}当前菜单信息`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
        // center: true,
        // roundButton: true,
      })
        .then(async () => {
          const response = await post(`${isEdit.value ? '/menu/update/' : '/menu/create/'}`, data.form);
          if (response.code == 200) {
            dialogFormVisible.value = false;
            await GetTreeMenuList();
            ElMessage({
              message: `${isEdit.value ? '修改' : '添加'}菜单信息成功`,
              type: 'success',
            });
          } else {
            dialogFormVisible.value = false;
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
          isEdit.value = false;
        })
        .catch(() => {
          isEdit.value = false;
        });
    };

    const handleDelete = (row) => {
      ElMessageBox.confirm('确定删除当前记录？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        // showCancelButton: false,
      })
        .then(async () => {
          const response = await post('/menu/delete/', { 'id': row.ID });
          if (response.code == 200) {
            await GetTreeMenuList();
            ElMessage({
              message: `成功删除 ${response.data.count} 条记录`,
              type: 'success',
            });
          } else {
            ElMessage({
              message: response.data.message,
              type: 'error',
            });
          }
        });
    };

    const showData = (row, bool, edit) => {
      dialogFormVisible.value = true;
      dialogDisabled.value = bool;
      isEdit.value = edit;
      if (!isEdit.value && !dialogDisabled.value) {
        data.form.id = '';
        data.form.name = '';
        // data.form.parentId = row.ID;
        data.form.orderNum = 0;
        data.form.path = '';
        // data.form.menuType = row.MENU_TYPE + 1;
        data.form.perms = '';
        data.form.remark = '';
        if (row == null) {
          data.form.parentId = '';
          data.form.menuType = 1;
        } else {
          data.form.parentId = row.ID;
          data.form.menuType = row.MENU_TYPE + 1;
        }
      } else {
        data.form.id = row.ID;
        data.form.name = row.NAME;
        data.form.parentId = row.PARENT_ID;
        data.form.orderNum = row.ORDER_NUM;
        data.form.path = row.PATH;
        data.form.menuType = row.MENU_TYPE;
        data.form.perms = row.PERMS;
        data.form.remark = row.REMARK;
      }
    };

    function MenuTypeInit(obj) {
      let val;
      if (obj instanceof Object) {
        val = obj.MENU_TYPE;
      } else {
        val = obj;
      }
      if (val == 1) {
        return '目录';
      } else if (val == 2) {
        return '菜单';
      } else if (val == 3) {
        return '按钮';
      }
    }

    onBeforeMount(async () => {
      await GetTreeMenuList();
      data.PERMISSION_BUTTON.CREATE = await hasPermission(MENU.SYSTEM_MENU_CREATE);
      data.PERMISSION_BUTTON.UPDATE = await hasPermission(MENU.SYSTEM_MENU_UPDATE);
      data.PERMISSION_BUTTON.DELETE = await hasPermission(MENU.SYSTEM_MENU_DELETE);
    });

    return {
      ...toRefs(data),
      dialogFormVisible,
      dialogDisabled,
      collapseColumn,
      showData,
      handleEdit,
      handleDelete,
      MenuTypeInit,
      ExpandChange,
      dayjs,
      isEdit,
      Search,
      ArrowLeft,
      ArrowRight,
    };
  },
};
</script>

<style scoped>
</style>
